<template>
  <!-- sku弹窗组件 -->
  <vk-data-goods-sku-popup 
      :modelValue="isShowSku"
      :mask-close-able="false"
      :localdata="goodsSkuList"
      :selected-init="true"
      :mode="2"
      add-cart-text="确定"
      add-cart-background-color="#27BA9B"
      :activedStyle="{
        color: '#27BA9B',
        borderColor: '#27BA9B',
        backgroundColor: '#E9F8F5'
      }"
      ref="goodsSkuPoup"
      @add-cart="onComfirmSelectSku"
      @close="isShowSku = false"
      @open="onOpenSkuPopup"
    />

  <div class="cart-container">
    <!-- 导航栏 -->
    <TmallNavBar>
      <template #left v-if="referer == 'goodsDetail'"><i class="icon iconfont icon-zuojiantou"></i></template>
      <template #default>购物车</template>
    </TmallNavBar>

    <!-- 有效的购物车商品列表 -->
    <div class="cart-list" v-if="cartStore.validList.length > 0">
      <!-- 优惠提示 -->
      <div class="tips">
        <span class="label">满减</span>
        <span class="desc">满1件, 即可享受9折优惠</span>
      </div>

      <!-- 滑动操作项 -->
      <van-swipe-cell
        v-for="item in cartStore.validList"
        :key="item.id"
        class="cart-swipe"
      >
        <!-- 商品信息 -->
        <div class="goods-wrap">
          <!-- 选中状态 -->
          <text 
            class="checkbox" 
            @click="checkOne(item.id, item.is_checked)" 
            :class="{ checked: item.is_checked == 1 ? true : false }"
          >
          </text>

          <img @click="$router.push('/goodsDetail?goods_id='+item.goods_id)" class="picture" :src="global.MINIO_FILE_DOMAIN + item.goods.cover_url" />


          <div class="meta">
            <div class="name ellipsis">{{ item.goods.name }}</div>

            <!-- SKU -->
            <div class="attrs-text" @click="selectGoodsSku(item)">
              {{ item.goods_sepc_option_text }}
            </div>

            <div class="price-count-box">
              <!-- 价格 -->
              <div class="price">{{ (item.new_price/100).toFixed(2) }}</div>
              <!-- 商品数量 -->
              <van-stepper
                disable-input
                background="#27BA9B"
                color="#fff"
                min="1"
                theme="round"
                v-model="item.num"
                :max="item.inventory_num"
                @change="changeNum($event, item)" 
              />
            </div>

            <!-- 降价提醒 -->
            <div class="goods-mark-down" v-if="item.goods.price > item.new_price">
              <span class="goods-mark-txt">比加入时降价</span>     
              <span class="mark-down-value">￥{{((item.goods.price - item.new_price)/100).toFixed(2)}}</span>
            </div>
          </div>
        </div>


        <!-- 右侧删除按钮 -->
        <template #right>
          <div class="cart-swipe-right">
            <van-button
              square text="删除" type="danger" class="delete-button"
              @click="deleteCartGoods(item)"
            >删除</van-button>
          </div>
        </template>
      </van-swipe-cell>
    </div>


    <!-- 购物车空状态 -->
    <div class="cart-blank" v-else>
      <van-image :src="blankCartImage" class="image" />
      <span class="text">购物车还是空的，快来挑选好货吧~</span>
      <van-button to="/" type="primary" round size="small" color="#27ba9b" class="button">去首页看看</van-button>
    </div>

    <!-- 无效的购物车商品 -->
    <div class="cart-list" v-if="cartStore.invalidList.length > 0">
      <!-- 优惠提示 -->
      <div class="tips">
        <span class="label" style="background-color: gainsboro;">失效商品</span>
      </div>

      <!-- 滑动操作项 -->
      <van-swipe-cell
        v-for="item in cartStore.invalidList"
        :key="item.id"
        class="cart-swipe"
      >
        <!-- 商品信息 -->
        <div class="goods-wrap">
          <div hover-class="none" class="navigator">

            <img class="picture" v-img-lazy="global.MINIO_FILE_DOMAIN + item.goods.cover_url" />

            <div class="meta">
              <div class="name ellipsis">{{ item.goods.name }}</div>

              <!-- SKU -->
              <div class="invalid-attrs-text">
                {{ item.goods_sepc_option_text }}
              </div>

              <div class="price-count-box">
                <!-- 价格 -->
                <div class="price">{{ (item.new_price/100).toFixed(2) }}</div>
              </div>

              <!-- 降价提醒 -->
              <div class="goods-mark-down" v-if="item.goods.price > item.new_price">
                <span class="goods-mark-txt">比加入时降价</span>      
                <text class="mark-down-value">￥{{((item.goods.price - item.new_price)/100).toFixed(2)}}</text>
              </div>
            </div>
          </div>
        </div>


        <!-- 右侧删除按钮 -->
        <template #right>
          <div class="cart-swipe-right">
            <van-button @click="deleteCartGoods(item)" class="button delete-button">删除</van-button>
          </div>
        </template>
      </van-swipe-cell>
    </div>

  </div>

  <!-- 吸底工具栏 -->
  <div class="toolbar">
    <span class="all" @click="checkAll" :class="{ checked: cartStore.isCheckAll }">全选</span>
    <span class="text">合计:</span>
    <span class="amount">{{ (cartStore.checkedAmount/100).toFixed(2) }}</span>
    <div class="button-grounp">
      <div @click="handlerSettle" class="button payment-button" :class="{ disabled: cartStore.checkedTotal == 0 ? true : false }">
        去结算({{ cartStore.checkedTotal }})
      </div>
    </div>
  </div>
</template>

<script setup>
import { reqGetGoodsSkuListAPI } from '@/apis/goods'
import { ref, inject, onMounted } from 'vue'
import { useCartStore } from '@/store/modules/cart'
import blankCartImage from '@/assets/images/blank_cart.png'
import { showConfirmDialog, showSuccessToast, showToast } from 'vant';
import {useRouter, useRoute} from 'vue-router'
import vkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue'

// -------------- 定义全局变量结束 ---------------
// 全局属性
const global = inject('global')

// 购物车存储
const cartStore = useCartStore()

// 路由器
const router = useRouter()

// 路由
const route = useRoute()
// -------------- 定义全局变量开始 ---------------



// ------------ 获取购物车列表功能开始 ------------
const isLoading = ref(true)
const referer = route.query.referer != undefined ? route.query.referer : ''
onMounted(async () => {
  isLoading.value = true
  await cartStore.getCartList()
  isLoading.value = false
})
// ------------ 获取购物车列表功能结束 ------------



// ------------ 删除购物车商品功能开始 ------------
const deleteCartGoods = (item) => {
	showConfirmDialog({
    title:'提示',
    message:'确定要删除该商品吗?'
  }).then(async () => {
    await cartStore.deleteCart(item.id)
    showSuccessToast('删除成功')
  }).catch(() => {})
}
// ------------ 删除购物车商品功能结束 ------------



// --------------- 商品SKU功能开始 ---------------
// 是否显示SKU弹窗
const isShowSku = ref(false)

// 组装的商品SKU列表
const goodsSkuList = ref({})

// 原始的商品SKU列表
const goodsSkus = ref([])

// 商品SKU弹层
const goodsSkuPoup = ref()

// 当前SKU
const currentSku = ref([])

// 当前购物车商品信息
const currentCartGood = ref({})

// 选择商品SKU
const selectGoodsSku = async (good) => {
  // 设置当前购物车商品
  currentCartGood.value = good

  // 获取商品SKU数据
  const result = await reqGetGoodsSkuListAPI({goods_id: good.goods_id, is_have_goods_option: 1, page_size: -1})

  // 商品SKU
  goodsSkus.value = result.data.goods_sku_items != null ? result.data.goods_sku_items.filter((item) => item.inventory_num > 0 && item.status == 1) : []
  

  // 商品选项
  let goodsOptions = result.data.goods_options != null ? result.data.goods_options.reverse() : []

  // 组装商品SKU列表
  goodsSkuList.value = {
    _id: good.goods_id,
    name: good.goods.name,
    goods_thumb: global.MINIO_FILE_DOMAIN + good.goods.cover_url,
    // sku_name_arr的数据顺序一定要和spec_list的数据顺序一致，坑坑坑的一逼
    // sku_name_arr ['荔枝纹杏色5.5cm', '38'] 与 spec_list {name: '颜色分类', list: Array(1)}{name: '尺码', list: Array(1)}
    sku_list: goodsSkus.value.map((item) => {
        // 如果商品SKU没有图片则使用商品封面图片
        let imgUrl =  item.img_url ? item.img_url : good.goods.cover_url
        return {
          _id: item.id,
          goods_id: good.goods_id,
          goods_name: good.goods.name,
          image: global.MINIO_FILE_DOMAIN + imgUrl,
          img: imgUrl,
          price: item.price,
          sku_name_arr: item.spec_option_value_items,
          stock: item.inventory_num,
        }
    }),
    spec_list: goodsOptions.map((item) => {
      let valueList = []
      let values = item.value.split(',')
      values.forEach((v) => {
        valueList.push({name: v})
      });
      return {
        name: item.name,
        list: valueList
      }
    }),
  }

  // 组装当前SKU值
  let goodsSepcOptions = good.goods_sepc_option_text.trim().split(' ')

  // 重置当前SKU值
  currentSku.value = []
  
  goodsSepcOptions.forEach((v) => {
    currentSku.value.push(v.split('：')[1])
  });

  // 将是否显示SKU设置为 true
  isShowSku.value = true
}

// 当sku弹层打开的时候执行，默认选中SKU选项
const onOpenSkuPopup = () => {
  goodsSkuPoup.value.selectSku({
    sku: currentSku.value,
    num: currentCartGood.value.num
  })
}

// 确定选择SKU
const onComfirmSelectSku = async (e) => {
  // 组装specsText
  let specsText = ''
  let goodsSku = goodsSkus.value.find((item) => item.id == e._id)
  if (goodsSku) {
    goodsSku.spec_option_values.forEach((v) => {
      specsText += v.name + "：" + v.value + " "
    });
  }
  
  // 如果sku选项没有变化，则不需要更新操作
  if (currentCartGood.value.goods_sku_id != e._id || currentCartGood.value.num != e.buy_num) {
    await cartStore.editCartSku({
      id: currentCartGood.value.id,
      num: e.buy_num,
      goods_cover_url: e.img,
      goods_name: e.goods_name,
      newSku: {
        skuId: e._id,
        price: e.price,
        goods_cover_url: e.img,
        inventory_num: e.stock,
        specsText,
      }
    })

    showSuccessToast('选择SKU成功')
  }
  
  // 关闭SKU弹窗
  isShowSku.value = false
}
// --------------- 商品SKU功能结束 ---------------



// --------------- 修改数量功能开始 ---------------
const changeNum = async (num, item) => {
  // 判断库存
  if (num > item.inventory_num) {
    showToast('库存不足!')
    return
  }
  
	await cartStore.editCart({ids: item.id + '', num})
	showSuccessToast('修改成功')
}
// --------------- 修改数量功能结束 ---------------



// --------------- 勾选商品功能开始 ---------------
// 延时器
const timer = ref(null)

// 单选商品
const checkOne =  (id, checked) => {
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout( async () => {
		await cartStore.editCart({ids: id + '', is_checked: checked == 1 ? 0 : 1})
		showSuccessToast('编辑成功')
	}, 500)
}
// --------------- 勾选商品功能结束 ---------------



// --------------- 全选商品功能结束 ---------------
const checkAll = async () => {
  if (cartStore.validList.length == 0) {
    return false
  }
  
	await cartStore.checkAllCart(!cartStore.isCheckAll)
}
// --------------- 全选商品功能结束 ---------------



// --------------- 结算跳转功能结束 ---------------
const handlerSettle = () => {
	if (cartStore.checkedTotal <= 0) {
    showToast('请勾选要结算的商品')
		return
	}
	
  router.push({path: '/confirmOrder',query: {mode:2}})
}
// --------------- 结算跳转功能结束 ---------------
</script>

<style scoped lang="scss">
.cart-container {
  height: 100%;
  margin-bottom: 100px;
  background: ghostwhite;
  // 购物车列表
  .cart-list {
    display: flex;
    flex-direction: column;
    padding: 40px 10px 0 10px;

    // 优惠提示
    .tips {
      display: flex;
      align-items: center;
      line-height: 1;
      margin: 15px 5px;
      font-size: 13px;
      color: #666;

      .label {
        color: #fff;
        padding: 4px 8px 3px;
        border-radius: 2px;
        font-size: 12px;
        background-color: #27ba9b;
        margin-right: 5px;
      }
    }

    // 购物车商品
    .cart-swipe {
      display: block;
      margin: 10px 0;
      .goods-wrap {
        display: flex;
        align-items: center;

        padding: 10px;
        border-radius: 5px;
        background-color: #fff;

        .checkbox {
          width: 40px;

          &::before {
            content: '\e615';
            font-family: 'iconfont' !important;
            font-size: 22px;
            color: #444;
          }

          &.checked::before {
            content: '\e605';
            color: #27ba9b;
          }
        }

        .picture {
          width: 85px;
          height: 85px;
        }

        .meta {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin-left: 10px;
          .name {
            height: 40px;
            line-height: 20px;
            font-size: 14px;
            color: #444;
          }

          .attrs-text {
            line-height: 1.8;
            padding: 0 8px;
            font-size: 12px;
            align-self: flex-start;
            border-radius: 4px;
            color: #888;
            background-color: #f7f7f8;
            border: 1px dashed gainsboro;
            margin: 10px 0 10px 0;
            &::after {
              font-family: "iconfont" !important;
              content: '\e60d';
            }
          }

          .invalid-attrs-text {
            line-height: 1.8;
            padding: 0 8px;
            font-size: 12px;
            align-self: flex-start;
            border-radius: 4px;
            color: #888;
            background-color: #f7f7f8;
            border: 1px dashed gainsboro;
            margin: 10px 0 10px 0;
          }

          .price-count-box {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items:center;
            .price {
              line-height: 1;
              font-size: 15px;
              color: #444;
              margin-bottom: 1px;
              color: #cf4444;
              &::before {
                content: '￥';
                font-size: 80%;
              }
            }
          }

          .goods-mark-down {
            display: flex;
            align-items: center;
            margin-top: 10px;
            font-size: 14px;
            .goods-mark-txt {
              color: #cf4444;
            }
            .mark-down-value {
              color: #27BA9B;
            }
          }
        }
      }
    }

    .cart-swipe-right {
      display: flex;
      height: 100%;

      .button {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50px;
        padding: 6px;
        line-height: 1.5;
        color: #fff;
        font-size: 13px;
      }

      .delete-button {
        background-color: #cf4444;
      }
    }
  }
}

.delete-button {
  height: 100%;
}


// 空状态
.cart-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: calc(100vh - 100px);
  .image {
    width: 200px;
    height: 140px;
  }
  .text {
    color: #444;
    font-size: 13px;
    margin: 13px 0;
  }
  .button {
    width: 120px !important;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  margin-bottom: 49px;
  height: 50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
  border-top: 1px solid #ededed;
  border-bottom: 1px solid #ededed;
  background-color: #fff;

  .all {
    margin-left: 13px;
    font-size: 14px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'iconfont' !important;
    content: '\e615';
    font-size: 20px;
    margin-right: 4px;
  }

  .checked::before {
    content: '\e605';
    color: #27ba9b;
  }

  .text {
    margin-right: 4px;
    margin-left: 16px;
    color: #444;
    font-size: 14px;
  }

  .amount {
    font-size: 20px;
    color: #cf4444;

    .decimal {
      font-size: 12px;
    }

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    position: absolute;
    right: 5px;
    top: 50%;

    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 36px;
    font-size: 13px;
    color: #fff;
    transform: translateY(-50%);

    .button {
      width: 120px;
      margin: 0 5px;
      border-radius: 36px;
    }

    .payment-button {
      background-color: #27ba9b;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
// 底部占位空盒子
.toolbar-height {
  height: 50px;
  box-sizing: content-box;
}
</style>